package com.sharer.last.utils;

import com.sharer.last.base.enums.ExceptionCode;
import com.sharer.last.base.exception.BusinessException;
import com.sharer.last.model.vo.QQInfoVO;
import com.sharer.last.service.OssFileService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * 获取QQ昵称头像信息
 *
 * @ClassName QQInfoUtils
 * @Author wangjin
 * @Date 2023/5/5 20:53
 * @Description
 * @Version 1.0
 */
@Component
public class QQInfoUtils {
    private static final String QQ_NICKNAME_URL  = "http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins={1}";
    private static final String QQ_NICKNAME_URL1 = "https://api.usuuu.com/qq/{1}";
    private static final String QQ_AVATAR_URL    = "https://q.qlogo.cn/g?b=qq&nk=%s&s=100";

    @Resource
    OssFileService ossFileService;

    @Resource
    RestTemplate restTemplate;

    /**
     * 获取QQ昵称
     *
     * @param qq
     * @return
     * @throws UnsupportedEncodingException
     */
    public String getQQNickname(String qq) throws UnsupportedEncodingException {
        String res      = restTemplate.getForObject(QQ_NICKNAME_URL, String.class, qq);
        byte[] bytes    = res.getBytes("iso-8859-1");
        String nickname = new String(bytes, "gb18030").split(",")[6].replace("\"", "");
        if ("".equals(nickname)) {
            return "nickname";
        }
        return nickname;
    }

    /**
     * 获取QQ头像URL
     *
     * @param qq
     * @return
     */
    public String getQQAvatarUrl(String qq){
        ResponseEntity<QQInfoVO> forEntity = restTemplate.getForEntity(QQ_NICKNAME_URL1, QQInfoVO.class, qq);
        QQInfoVO                 body      = forEntity.getBody();
        if (body == null) {
            throw new BusinessException(ExceptionCode.BUSINESS_FAIL);
        }
        QQInfoVO.QQData data = body.getData();
        if (data == null) {
            throw new BusinessException(ExceptionCode.BUSINESS_FAIL);
        }
        String avatar = data.getAvatar();
        return ossFileService.upload(avatar,".png");
    }

    /**
     * 判断是否QQ号
     *
     * @param number
     * @return
     */
    public static boolean isQQNumber(String number) {
        return number.matches("^[1-9][0-9]{4,10}$");
    }
}
